import {Button, Form, Input, Select, Upload, Switch, DatePicker, Space, ConfigProvider, InputNumber} from "antd";
import API from "../../api/api";
import moment from 'moment';
import { UploadOutlined } from '@ant-design/icons';
import React, {useState} from "react";
import Edit from "../CKEditor/Edit";
import locale from 'antd/lib/date-picker/locale/zh_CN';
import {config, url} from "../../util/config";
import PicturesWall from "../IndexManage/PicturesWall";

const {RangePicker } = DatePicker;
let token = localStorage.getItem("token")

export default function UpdateFormForActivity(props){
    let [editorVisible,setEditorVisible] = useState(null)
    const [form] = Form.useForm();
    let imageUrl = undefined;
    //文件上传默认显示的内容
    //是否执行了刷新
    let hasFlashed = false;
    const defaultData = API.getActivityContent(props.data.key);;
    let obj = {uid:1,status:"done",url:defaultData.figure};

    let applyStartTime = null;
    let applyEndTime = null;
    let startTime = null;
    let endTime = null;

    const onReset = () => {
        alert("reset")
        form.resetFields();
    };

    const request = {
        action: url.file_upload_url,
        headers: {
            'Accept': "application/json",
            'Authorization': token
        },
        defaultFileList: []
    }

    const onFinish = (values) => {
        if(values.station==""){
            values.station=" ";
        }
        if(values.desc==""){
            values.desc=" ";
        }
        values.figure = imageUrl;
        if(values.new==defaultData.new && values.name==undefined&&values.figure==undefined&&values.desc==undefined&&values.startTime==undefined&&values.applyStartTime==undefined&&values.status==undefined&&values.station==undefined&&values.attach==undefined&&(editorVisible==null || editorVisible=="" || editorVisible=="<p></p>" || editorVisible==defaultData.content)){
            alert("内容未修改");
            return
        }else {
            if(values.new==null || values.new==""){
                values.new = config.notify_date
            }
            if(applyStartTime!=null && applyEndTime!=null){
                values.applyStartTime = applyStartTime;
                values.applyEndTime = applyEndTime
            }
            if(startTime!=null && endTime!=null){
                values.startTime = startTime;
                values.endTime = endTime;
            }
            if( editorVisible=="<p></p>" || editorVisible=="" || editorVisible=="<span></span>"){
                alert("文章内容不可为空");
                return;
            }else if(editorVisible==defaultData.content){
                console.log("内容未修改")
                values.content = undefined
            }else if(editorVisible==null){
                values.content = undefined
            }else {
                values.content = editorVisible
            }
            if(values.attach!=undefined){
                values.attachUrls = []
                values.attachNames = []
                values.attachNum = 0
                let tmpList = values.attach.fileList;
                for(let i=0;i<tmpList.length;i++){
                    if(tmpList[i].url==undefined){
                        values.attachUrls.push(tmpList[i].response.result[0].FILE_URL)
                        values.attachNames.push(tmpList[i].response.result[0].FILE_URL_NAME)

                    }else {
                        values.attachUrls.push(tmpList[i].url)
                        values.attachNames.push(tmpList[i].name)
                    }
                    ++values.attachNum
                }
                if(values.attachUrls==defaultData.attachUrls && values.attachNames==defaultData.attachNames){
                    values.attachUrls = undefined
                    values.attachNames = undefined
                    values.attachNum = undefined
                }
            }
            values.key = defaultData.key;
            if(values.status==true){
                values.status='Y'
            }else if(values.status==false){
                values.status='N'
            }
            console.log('Received values of form: ', values);
            if(API.updateActivity(values)=="ok"){
                if(!hasFlashed){
                    //只有返回成功后，才会置父组件的状态值为true，即Modal关闭后实现列表刷新
                    props.result(true)
                    //执行上一步后，再本组件也加一个标记，来标识已经重置了父组件的刷新状态值status
                    hasFlashed = true;
                }
            }
        }

    };


    function getImageUrl(url){
        debugger
        if(url==""){
            imageUrl = -1
        }else {
            imageUrl = url
        }
    }

    const getFileList=()=>{
        for(let i = 0;i<defaultData.attachNum;i++){
            request.defaultFileList.push({
                uid:i,
                name:defaultData.attachNames[i],
                status:'done',
                url:defaultData.attachUrls[i]
            })
        }
    }

    function getContent(content) {
        // data = content
        editorVisible = content
    }

    // const dateFormat = 'Wed MM DD YYYY HH:mm:ss';
    const dateFormat = 'YYYY-MM-DD HH:mm:ss';

    function getApplyStartAndEndTime(value, dateString) {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
        applyStartTime = dateString[0];
        applyEndTime = dateString[1];
    }

    function getStartAndEndTime(value, dateString) {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
        startTime = dateString[0]
        endTime = dateString[1]
    }

    getFileList();

    return (
        <Form
            preserve={false}
            form={form}
            onFinish={onFinish}
            onReset={onReset}
            labelCol={{
                span: 4,
            }}
            wrapperCol={{
                span: 17,
            }}
            layout="horizontal"
            initialValues={{
                ['new']: defaultData.new
            }}
        >
            <Form.Item label="活动标题" name="name">
                <Input defaultValue={defaultData.name}/>
            </Form.Item >
            <Form.Item label="活动描述" name={"desc"}>
                <Input defaultValue={defaultData.desc}/>
            </Form.Item>
            <Form.Item label="活动配图" name={"figure"} >
                <PicturesWall defaultValue={obj} render={getImageUrl}/>
            </Form.Item>
            <Form.Item label="提醒時間【天數】" name="new">
                <InputNumber min={1} placeholder={`默認${config.notify_date}天`}/>
            </Form.Item>
            <Form.Item label="是否置顶" name={"status"} >
                <Switch defaultChecked={defaultData.status=='N'?false:true}/>
            </Form.Item>
            <Form.Item label="报名时间" name={"applyStartTime"} >
                <RangePicker showTime locale={locale} onChange={getApplyStartAndEndTime} defaultValue={defaultData.applyStartTime==""?null:[moment(defaultData.applyStartTime, dateFormat), moment(defaultData.applyEndTime, dateFormat)]} format={dateFormat}/>
            </Form.Item>
            <Form.Item label="活动时间" name={"startTime"} >
                <RangePicker showTime locale={locale} onChange={getStartAndEndTime} defaultValue={defaultData.startTime==""?null:[moment(defaultData.startTime, dateFormat), moment(defaultData.endTime, dateFormat)]} format={dateFormat}/>
            </Form.Item>
            <Form.Item label="活动地点" name={"station"} >
                <Input defaultValue={defaultData.station}/>
            </Form.Item>
            <Form.Item label="活动附件" name={"attach"} >
                <Upload name="file" {...request} listType="picture" >
                    <Button icon={<UploadOutlined></UploadOutlined>}>上传</Button>
                </Upload>
            </Form.Item>
            <Form.Item
                name="content"
                label="活动内容"
            >
                <Edit data={defaultData.content} onChange={getContent}></Edit>
            </Form.Item>
            <Form.Item
                label="提交修改"
                name="commit"
            >
                <Button type="primary" htmlType="submit">
                    提交
                </Button>
                <Button htmlType="reset" style={{marginLeft:"1rem"}}>
                    重置
                </Button>
            </Form.Item>
        </Form>
    );
}
